package com.njtoyo.taxi.admin.rest.controller.business;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.IoUtil;
import cn.hutool.core.lang.Dict;
import cn.hutool.core.util.StrUtil;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import cn.hutool.poi.excel.StyleSet;
import com.njtoyo.taxi.admin.service.business.ServiceFeeService;
import com.taxi.entity.common.RestResult;
import org.apache.poi.ss.usermodel.CellStyle;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.*;

@RestController
@RequestMapping("business/service-fee")
public class ServiceFeeController {

    @Autowired
    private ServiceFeeService serviceFeeService;


    @GetMapping("/export")
    public void export(@RequestParam(required = false) String startDate, @RequestParam(required = false) String endDate, HttpServletResponse response)
            throws IOException {
        Date startDateTime = DateUtil.offsetDay(DateUtil.date(), -30);
        Date endDateTime = DateUtil.date();
        if (StrUtil.isNotBlank(startDate) && StrUtil.isNotBlank(endDate)) {
            startDateTime = DateUtil.parseDateTime(startDate);
            endDateTime = DateUtil.parseDateTime(endDate);
        }
        List<Dict> list = serviceFeeService.getExportData(DateUtil.beginOfDay(startDateTime), DateUtil.endOfDay(endDateTime));
        List<Map<String, Object>> rows = new ArrayList<>();
        for (Dict dict : list) {
            Map<String, Object> row = new HashMap<>();
            row.put("日期", dict.getStr("date"));
            row.put("服务费", dict.getStr("fee"));
            rows.add(row);
        }

        ExcelWriter writer = ExcelUtil.getWriter();
        StyleSet style = writer.getStyleSet();
        CellStyle cellStyle = style.getHeadCellStyle();
        cellStyle.setWrapText(true);
        writer.write(rows, true);
        response.setContentType("application/vnd.ms-excel;charset=utf-8");
        response.setHeader("Content-Disposition", "attachment;filename=cars.xls");
        ServletOutputStream out = response.getOutputStream();

        writer.flush(out, true);
        writer.close();
        IoUtil.close(out);

    }
}
